<template>
    <div class="repair">
        <van-form show-error scroll-to-error label-width="25vw" @submit="onSubmit" @failed="onFailed">
            <MyTitle>墓位信息</MyTitle>
            <!-- <van-field 
                v-model="formData.gsy_ex100" 
                :readonly="isReadonly"
                required
                center
                name="gsy_ex100" 
                label="墓位"
                placeholder="墓位" 
                :rules="[{ required: true, message: '请填写墓位' }]"
            /> -->
            <FieldPopupCascader
                :field="gsy_ex100"
                @update:field="gsy_ex100Change"
                name="gsy_ex100"
                label="墓区"
                :options="columns1"
                confirmType="selectedOptions"
                :readonly="false"
            />
            <FieldPopupPicker
                v-if="gsy_ex100"
                :field="gsy_mainid"
                @update:field="gsy_mainidChange"
                :required="true"
                name="gsy_mainid"
                label="墓穴编号"
                :columns="columns2"
                confirmType="selectedOptions"
                :readonly="isReadonly"
            />
            <MyTitle>联系人信息</MyTitle>
            <van-field
                v-model="formData.ro_ex1"
                :readonly="isReadonly"
                required
                center
                name="ro_ex1"
                label="联系人姓名"
                placeholder="联系人姓名"
                :rules="[{ required: true, message: '请填写联系人姓名' }]"
            >
                <template v-if="!isReadonly" #button>
                    <van-uploader
                        v-model="dataArr.sh_ex37"
                        :readonly="isReadonly"
                        :preview-image="false"
                        :before-delete="beforeDelete('sh_ex37')"
                        :before-read="beforeRead"
                        :after-read="afterRead('sh_ex37', true)"
                    >
                        <van-button size="small" icon="plus" type="primary" native-type="button">拍照识别</van-button>
                    </van-uploader>
                </template>
            </van-field>
            <van-field
                v-model="formData.ro_ex2"
                :readonly="isReadonly"
                required
                center
                type="number"
                maxlength="11"
                name="ro_ex2"
                label="联系电话"
                placeholder="联系电话"
                :rules="[
                    { required: true, message: '请填写联系电话' },
                    { validator: isPhone, message: '请填写正确的联系电话' },
                ]"
            />

            <van-field
                v-model="formData.ro_ex12"
                :readonly="isReadonly"
                required
                center
                name="ro_ex12"
                label="联系人身份证"
                placeholder="联系人身份证"
                :rules="[
                    { required: true, message: '请填写联系人身份证' },
                    { validator: validator3, message: '请填写正确的联系人身份证' },
                ]"
            />
            <MyTitle>祭祀信息</MyTitle>
            <FieldPopupDatePicker
                v-model:field="formData.gsy_dat1"
                :required="true"
                :minDate="new Date()"
                name="gsy_dat1"
                label="祭扫日期"
                :readonly="isReadonly"
            />
            <FieldPopupTimePicker
                v-model:field="formData.gsy_dat2"
                :required="true"
                :minTime="minTime"
                name="gsy_dat2"
                label="祭扫时间"
                :readonly="isReadonly"
            />

            <van-field
                v-model="formData.ro_ex3"
                :readonly="isReadonly"
                required
                center
                name="ro_ex3"
                label="祭扫备注"
                placeholder="祭扫备注"
                :rules="[{ required: true, message: '请填写祭扫备注' }]"
            />
            <MyTitle>祭扫服务</MyTitle>
            <template v-for="(item, index) in serviceData" :key="index">
                <van-card
                    :price="item.sf_ex9"
                    :desc="item.sf_ex19"
                    :title="item.sf_ex2"
                    :thumb="item.sf_ex50"
                    lazy-load
                >
                    <template #footer>
                        <van-stepper v-model="item.sf_ex13" integer default-value="0" min="0" @change="onStepChange" />
                    </template>
                </van-card>
            </template>
            <div class="total-amount">
                <div>总金额：</div>
                <div>{{ totalAmount }}</div>
            </div>

            <!-- <van-field 
                required
                readonly
                center
                name="sh_ex37" 
                label="联系人身份证"
                :rules="[{ validator: validator2('sh_ex37'), message: '请上传联系人身份证' }]"
            />
            <div class="uploader-box">
                <van-uploader 
                    v-model="dataArr.sh_ex37" 
                    :readonly="isReadonly"
                    :max-count="1" 
                    upload-text="联系人身份证" 
                    :before-delete="beforeDelete('sh_ex37')" 
                    :before-read="beforeRead" 
                    :after-read="afterRead('sh_ex37')"
                    :deletable="!isReadonly"
                >
                    <template #default>
                        <img src="@/assets/uploader/uploader.png" />
                    </template>
                </van-uploader>
            </div> -->
            <FixedButton v-if="!isReadonly" native-type="submit">提交</FixedButton>
        </van-form>
    </div>
</template>

<script lang="ts" setup>
    // import { ref, reactive, markRaw, onBeforeMount } from 'vue';
    import type { Ref, Raw } from 'vue';
    import { useRouter, useRoute } from 'vue-router';
    // import { showDialog, showLoadingToast, closeToast, showFailToast } from 'vant';
    import MyTitle from '@/components/myTitle/MyTitle.vue';
    import FixedButton from '@/components/fixedButton/FixedButton.vue';
    import FieldPopupPicker from '@/components/fieldPopupPicker/FieldPopupPicker.vue';
    import FieldPopupDatePicker from '@/components/fieldPopupDatePicker/FieldPopupDatePicker.vue';
    import FieldPopupTimePicker from '@/components/fieldPopupTimePicker/FieldPopupTimePicker.vue';
    import FieldPopupCascader from '@/components/fieldPopupCascader/FieldPopupCascader.vue';

    import FieldPopupEsign from '@/components/FieldPopupEsign.vue';
    import { useWeixinLogin3 } from '@/hooks';
    import {
        saveReplaceVisitAGraveApi,
        fileUploadBase64ExApi,
        idOrcApi,
        wechatPayApi,
        getAareaApi,
        getCemeteryApi,
        getPackageListApi,
    } from '@/apis';
    import { isPhone, compressImg, isCardID, getSex, getAge } from '@/utils';
    import { useStore } from '@/store';
    // 微信授权并且跳转到对应页面
    useWeixinLogin3('sacrificeAndSweepForGuests');
    const router = useRouter();
    const route = useRoute();
    const store = useStore();
    const isReadonly: boolean = false;

    const columns1: Ref<
        {
            text: string;
            value: string;
        }[]
    > = ref([
        // { text: '墓穴1', value: '墓穴1' },
        // { text: '墓穴2', value: '墓穴2' },
    ]);
    const columns2: Ref<
        {
            text: string;
            value: string;
        }[]
    > = ref([
        // { text: '编号1', value: '编号1' },
        // { text: '编号2', value: '编号2' },
    ]);
    onBeforeMount(async () => {
        showLoadingToast({
            message: '加载中...',
            forbidClick: true,
            duration: 0,
        });
        getAareaApi({
            iszj: 'N',
            time: new Date().getTime().toString(),
            company: '海陵区凤栖园智慧墓园系统',
        })
            .then((res) => {
                let forFun = (arr2) => {
                    arr2.forEach((item, index) => {
                        item.value = item.id;
                        item.text = item.text;
                        if (item.child.length > 0) {
                            item.children = item.child;
                            forFun(item.children);
                        }
                    });
                };
                forFun(res[0].child);
                columns1.value = res[0].child;
            })
            .finally(() => {
                closeToast();
            });
        if (isReadonly) {
            console.log('...........');
            // 获取数据
        } else {
            getPackageListApi({}).then((res: any) => {
                serviceData.value = res.data[0].goods;
                onStepChange('');
            });
        }
    });
    const gsy_ex100Change = (val) => {
        gsy_ex100.value = '';
        val.forEach((item, index) => {
            if (val.length == index + 1) {
                gsy_ex100.value += item.text;
                formData.value.gsy_ex100 = item.value;
            } else {
                gsy_ex100.value += item.text + '/';
            }
        });
        formData.value.gsy_mainid = '';
        gsy_mainid.value = '';
        showLoadingToast({
            message: '加载中...',
            forbidClick: true,
            duration: 0,
        });
        columns2.value = [];
        getCemeteryApi({
            areaId: formData.value.gsy_ex100,
            company: '海陵区凤栖园智慧墓园系统',
        })
            .then((res: any) => {
                res.data[0]?.child.forEach((item, index) => {
                    item.text = item.gm_ex6;
                    item.value = item.gm_id;
                });
                columns2.value = res.data[0].child;
            })
            .finally(() => {
                closeToast();
            });
    };
    const gsy_mainidChange = (val) => {
        gsy_mainid.value = val.text;
        formData.value.gsy_mainid = val.value;
    };

    let currentTime: any = new Date();
    currentTime.setHours(currentTime.getHours() + 1);
    console.log(currentTime.getHours().toString().padStart(2, '0'));
    console.log(currentTime.getMinutes().toString().padStart(2, '0'));
    currentTime = currentTime.getHours().toString().padStart(2, '0') + ':00:00';
    console.log(currentTime);
    // let minTime = currentTime
    const minTime: Ref<string> = ref(currentTime);
    const gsy_ex100: Ref<string> = ref('');
    const gsy_mainid: Ref<string> = ref('');

    const formData = ref({
        ro_ex2: '',
        ro_ex1: '',
        ro_ex12: '',
        sh_ex37: '',
        ro_ex3: '',
        ro_dat1: '',
        gsy_dat1: '',
        gsy_dat2: '',
        gsy_ex100: '',
        gsy_mainid: '',
        openid: store.openid,
        token: store.openid,
    });
    const dataArr = reactive({
        sh_ex37: [], //联系人身份证
    });

    // 照片数组验证
    const validator2 = (field) => {
        return (val) => {
            console.log(val);
            console.log(field);
            if (dataArr[field].length == 0 || !formData.value[field]) {
                return false;
            } else {
                return true;
            }
        };
    };
    // 校验函数返回 true 表示校验通过，false 表示不通过
    const validator3 = (val) => {
        if (isCardID(val)) {
            return false;
        } else {
            return true;
        }
    };
    const beforeDelete = (data) => {
        return (file, detail) => {
            let arr = formData.value[data].split(',');
            arr.splice(detail.index, 1);
            formData.value[data] = arr.join(',');
            return true;
        };
    };
    const beforeRead = (file) => {
        console.log(file);
        if (file.type !== 'image/jpeg' && file.type !== 'image/png') {
            showFailToast('请上传 jpg/png 格式图片');
            return false;
        }
        return true;
    };
    const afterRead = (imgField, isIdOrc = false) => {
        return (file) => {
            file.status = 'uploading';
            file.message = '上传中...';
            // 执行压缩图片并上传
            let obj = new compressImg(file, afterRead2, imgField, isIdOrc, file);
            // console.log(obj)
            // console.log(obj.getMyf())
            // console.log(obj.getMyfb())
            // console.log(obj.myf)
            // console.log(obj.myfb)
        };
    };
    // 组件方法 获取 流
    const afterRead2 = (imgField, isIdOrc, file, obj) => {
        // failed done
        // file.status = 'uploading';
        // file.message = '上传中...';
        // file.file: 文件 file.content: base64图片
        console.log(file);
        // let f = new FormData()
        // f.append('file', file.file)
        fileUploadBase64ExApi({
            data: obj,
            sCode: 'fhsxbyg',
        })
            .then((res) => {
                // file.status = 'done';
                // file.message = '上传完成';
                console.log(res);

                if (imgField == 'sh_ex37') {
                    // 拍照识按钮要显示不能设置maxCount=1，不然上传一张图就没了按钮
                    if (dataArr[imgField].length > 1) {
                        dataArr[imgField].shift();
                    }
                    formData.value[imgField] = res[0].url;
                    // 用过拍照识别后续上传身份证都要进行idOrc验证信息
                    if (isIdOrc) {
                        idOrcApi({
                            img: obj,
                        })
                            .then((res: any) => {
                                if (res.idcard_number_type == 1) {
                                    let obj = res.words_result;

                                    if (imgField == 'sh_ex37') {
                                        formData.value.ro_ex1 = obj['姓名'].words;
                                        formData.value.ro_ex12 = obj['公民身份号码'].words;
                                    }
                                } else {
                                    throw new Error('身份证验证失败');
                                }
                                file.status = 'done';
                                file.message = '上传完成';
                            })
                            .catch((err) => {
                                console.log(err);
                                showFailToast('识别失败');
                                file.status = 'done';
                                file.message = '上传完成';
                            });
                    } else {
                        file.status = 'done';
                        file.message = '上传完成';
                    }
                } else {
                    // formData.value[imgField] = res[0].url
                    if (formData.value[imgField]) {
                        formData.value[imgField] = formData.value[imgField].concat(',', res[0].url);
                    } else {
                        formData.value[imgField] = formData.value[imgField].concat(res[0].url);
                    }
                    file.status = 'done';
                    file.message = '上传完成';
                }
            })
            .catch((err) => {
                file.status = 'failed';
                file.message = '上传失败';
                console.log(dataArr[imgField]);
                dataArr[imgField].pop();
                showFailToast('上传失败');
                console.log(err);
            });
    };

    const onFailed = (value) => {
        showDialog({
            title: '提示',
            message: value.errors[0].message,
        });
    };

    const serviceData: Ref<any> = ref([
        // {
        //     sf_id: '', //服务项目id
        //     sf_ex2: '',//服务项目名称
        //     sf_ex8: '',//单位
        //     sf_ex9: '',//单价
        //     sf_ex13: '',//数量
        //     sf_ex19: '',//小类别 花圈 花篮
        //     sf_ex50: 'https://fastly.jsdelivr.net/npm/@vant/assets/ipad.jpeg',//图片
        // }
    ]);
    const totalAmount: Ref<number> = ref(0); //总选择金额
    const onStepChange = (val) => {
        // val.roc_ex4 = val.sf_ex9 * val.sf_ex13
        totalAmount.value = 0;
        serviceData.value.forEach((item, index) => {
            item.roc_ex4 = 0;
            if (item.sf_ex13 > 0) {
                totalAmount.value += item.sf_ex9 * item.sf_ex13;
                item.roc_ex4 = item.sf_ex9 * item.sf_ex13;
            }
        });
    };

    const onSubmit = async (value) => {
        if (totalAmount.value <= 0) {
            return showFailToast('请选择祭扫服务');
        }
        showLoadingToast({
            message: '加载中...',
            forbidClick: true,
            duration: 0,
        });
        formData.value.ro_dat1 = formData.value.gsy_dat1 + ' ' + formData.value.gsy_dat2;
        saveReplaceVisitAGraveApi({
            data: JSON.stringify(formData.value),
            item: JSON.stringify(serviceData.value),
            // data: formData.value,
        })
            .then((res) => {
                closeToast();
                if (res[0].status == '+OK') {
                    showDialog({
                        title: '提示',
                        message: res[0].msg,
                    }).then(() => {
                        router.push('/');
                    });
                    // onSubmit2()
                } else {
                    showDialog({
                        title: '提示',
                        message: '网络异常，请稍后重试！',
                    });
                }
            })
            .catch((err) => {
                closeToast();
                showDialog({
                    title: '提示',
                    message: '网络异常，请稍后重试！',
                });
            });
    };

    const onSubmit2 = async () => {
        showLoadingToast({
            message: '加载中...',
            forbidClick: true,
            duration: 0,
        });
        try {
            // let res1 = await weixinCgiBinAccessTokenApi({
            // 	grant_type: 'client_credential',
            // 	appid: 'wx8c16179b5b100339',
            // 	secret: 'acd91a6cac2144fec8a1c684fae2b09e',
            // })
            // let res2 = await weixinGetticketApi({
            // 	access_token: res1.access_token,
            // 	type: 'jsapi',
            // })
            // wx.config({
            // 	debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
            // 	appId: 'wx8c16179b5b100339', // 必填，公众号的唯一标识
            // 	timestamp: new Date().getTime(), // 必填，生成签名的时间戳
            // 	nonceStr: '', // 必填，生成签名的随机串
            // 	signature: '',// 必填，签名
            // 	jsApiList: [] // 必填，需要使用的JS接口列表
            // });
            let dat = {
                openid: store.openid,
                ...formData,
            };
            console.log(JSON.stringify(dat));
            // alert(JSON.stringify(dat))
            let res1 = await wechatPayApi({
                openid: store.openid,
                ...formData,
            });
            // 第二个参数需要后端返回签名认证
            // let res2 = await jsapiApi({
            // 	appid: res1.wxAppId, //公众号ID
            // 	mchid: '1656768053', //直连商户号
            // 	description: '墓位续费', //商品描述
            // 	out_trade_no: res1.wxNonceStr, //商户系统内部订单号，只能是数字、大小写字母_-*且在同一个商户号下唯一。
            // 	// out_trade_no: new Date().getTime().toString() + Math.floor(Math.random()*1000000).toString().padStart(6, '0'), //商户系统内部订单号，只能是数字、大小写字母_-*且在同一个商户号下唯一。
            // 	notify_url: 'http://ysx.tianxunwang.com/fhsWeixin/renew', // 异步接收微信支付结果通知的回调地址，通知URL必须为外网可访问的URL，不能携带参数。 公网域名必须为HTTPS，如果是走专线接入，使用专线NAT IP或者私有回调域名可使用HTTP
            // 	amount: {
            // 		total: formData.money * 100 //订单总金额，单位为分。
            // 	}, //订单金额信息
            // 	payer: {
            // 		openid: store.openid //用户在普通商户AppID下的唯一标识。
            // 	}, // 支付者信息。
            // }, res1.wxPaySign)
            if (typeof WeixinJSBridge == 'undefined') {
                if (document.addEventListener) {
                    document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                } else if (document.attachEvent) {
                    document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                    document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                }
            } else {
                onBridgeReady(res1);
            }
        } catch (error) {
            showDialog({
                title: '提示',
                message: '网络异常，请稍后重试！',
            });
        } finally {
            closeToast();
        }
    };
    const onBridgeReady = (res1) => {
        // let appId = "wx8c16179b5b100339"
        let appId = res1.wxAppId;
        let timestamp = res1.wxTimeStamp;
        let nonceStr = res1.wxNonceStr;
        let package1 = res1.wxPackage;
        let paySign = res1.wxPaySign;
        let signType = res1.wxSignType;
        WeixinJSBridge.invoke(
            'getBrandWCPayRequest',
            {
                appId: appId, //公众号ID，由商户传入
                timeStamp: timestamp, //时间戳，自1970年以来的秒数
                nonceStr: nonceStr, //随机串
                package: package1,
                // "signType": "RSA",     //微信签名方式
                signType: signType, //微信签名方式
                // "paySign": "oR9d8PuhnIc+YZ8cBHFCwfgpaK9gd7vaRvkYD7rthRAZ\/X+QBhcCYL21N7cHCTUxbQ+EAt6Uy+lwSN22f5YZvI45MLko8Pfso0jm46v5hqcVwrk6uddkGuT+Cdvu4WBqDzaDjnNa5UK3GfE1Wfl2gHxIIY5lLdUgWFts17D4WuolLLkiFZV+JSHMvH7eaLdT9N5GBovBwu5yYKUR7skR8Fu+LozcSqQixnlEZUfyE55feLOQTUYzLmR9pNtPbPsu6WVhbNHMS3Ss2+AehHvz+n64GDmXxbX++IOBvm2olHu3PsOUGRwhudhVf7UcGcunXt8cqNjKNqZLhLw4jq\/xDg==" //微信签名
                paySign: paySign, //微信签名
            },
            function (res) {
                console.log(res);
                if (res.err_msg == 'get_brand_wcpay_request:ok') {
                    // 使用以上方式判断前端返回,微信团队郑重提示：
                    //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。
                    router.push('/');
                } else {
                    showDialog({
                        title: '提示',
                        message: '支付异常，请稍后重试！',
                    });
                }
            }
        );
    };
</script>
<style lang="scss" scoped>
    .repair {
        height: 100vh;
        overflow: hidden;
        display: flex;
        flex-direction: column;
    }
    :deep(.van-form) {
        // height: 550px;
        // height: 510px;
        flex: 1;
        overflow: scroll;
    }
    .uploader-box {
        border-bottom: 1px solid #999999;
        margin: 6px 15px;
        box-sizing: border-box;
        padding: 0px 0;
        height: 180px;
        overflow: hidden;
        img {
            width: 345px;
            height: 180px;
        }
        // 上传图片后图片大小
        :deep(.van-uploader__preview-image) {
            width: 345px;
            height: 180px;
        }
    }
    .my-card {
        background: #fff;
        border-bottom: 1px solid #efefef;
    }
    .dnt-box {
        border-bottom: 1px solid #efefef;
    }

    .total-amount {
        display: flex;
        justify-content: flex-end;
        align-items: center;
        height: 50px;
        :nth-child(2) {
            width: 50px;
            height: 100%;
            display: flex;
            align-items: center;
        }
    }
</style>
